import { Component, OnInit, Input, ElementRef, SimpleChanges } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GanttService } from '../../../services/gantt-chart/gantt.service';
import { NzNotificationService } from 'ng-zorro-antd';
import * as moment from 'moment';
import { ModelService } from '../../../services/model/model.service';
import { GanttApi } from '../../../services/gantt-chart/gantt.api';
import { GanttModel, EditModel } from '../../../services/gantt-chart/gantt.model';
import { element } from 'protractor';
// import { GanttPermission } from '../../../services/gantt-chart/gantt.permission';

declare var Neon: any;
@Component({
  selector: 'app-task-box',
  templateUrl: './task-box.component.html',
  styleUrls: ['./task-box.component.scss']
})
export class TaskBoxComponent implements OnInit {
  @Input() public leftPanel: number;
  
  public isVisible = false;
  public currentDate = moment();
  public taskNameWidth = 100;
  public prevTaskWidth = 0;
  public headerWidth = 340;
  public otherWidthTotal = 340;
  public actualDisabled = true;
  public isAllselected = false;

  // 前置任务编辑器

  public editPermission = true;
  public constructor(
    public ganttService: GanttService,
    private elementRef: ElementRef,
    private _notification: NzNotificationService,
    private modelService: ModelService,
    private ganttApi: GanttApi,
    private activatedRoute: ActivatedRoute
  ) {
  }

  public ngOnInit() {

  }

  public ngOnChanges(changes: { [propName: string]: SimpleChanges }) {
    if (changes['leftPanel'] && changes['leftPanel'].previousValue != changes['leftPanel'].currentValue) {
      this.headerWidth = this.taskNameWidth + this.otherWidthTotal > this.leftPanel ? this.taskNameWidth + this.otherWidthTotal : this.leftPanel;
    }
  }

  /*
    单元格拖动条
  */
  public dragstartHandler(e: any, model: string) {
    e.stopPropagation();
    let startX = e.clientX;
    //let viewCtWidth=document.getElementById("viewCtDiv").clientWidth;
    let dragHandler = (e) => {
      if (model === 'taskName') {
        this.taskNameWidth += (e.clientX - startX);
      }
      if (model === 'prevTask') {
        this.prevTaskWidth += (e.clientX - startX);
      }
      this.headerWidth = this.taskNameWidth + this.prevTaskWidth + this.otherWidthTotal > this.leftPanel ? this.taskNameWidth + this.prevTaskWidth + this.otherWidthTotal : this.leftPanel;
      startX = e.clientX;
    };

    let dragendHandler = (e) => {
      document.documentElement.removeEventListener('mousemove', dragHandler, false);
      document.documentElement.removeEventListener('mouseup', dragendHandler, false);
    };
    document.documentElement.addEventListener('mouseup', dragendHandler, false);
    document.documentElement.addEventListener('mousemove', dragHandler, false);
  }

  /*
   双击前置任务
  */


  // bindingAttrs(task: GanttModel) {
  //   console.log(task);
  //   let uuids = [];
  //   let bindings = task.bindings;
  //   if (bindings && bindings.length > 0) {
  //     bindings.forEach(item => {
  //       uuids.push(item.uuid)
  //     })
  //     this.modelService.currentUUid = uuids;
  //     this.modelService.addCustomAttr();
  //   } else {
  //     this.createNotification('error', '该任务没绑定构件', '')
  //   }
  // }


  // 工期blur

  /*
  工作安排中， 禁用计划完成时间早于当前时间的任务
  */
  public isBeforeCurrent(endDate: any) {
    let isPlanning = false;
    if (isPlanning) {
      let currentDate = this.currentDate;
      let isBefore = moment(endDate).isBefore(currentDate);
      if (isBefore) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }


  /*
  * 时间选择器
  */
  public dateClickTask(task: any) {
    this.updateServiceData();
  }
  // prevTaskChange(task, eq) {
  //   let prevTask = task.prevTask;
  //   let id = task.id;
  //   if (prevTask) {
  //     let prevArray = prevTask.split(",");
  //     if (this.checkPrevTask(prevArray, id, eq)) {
  //       // console.log(this.checkPrevTask(prevArray, id, eq))
  //     }
  //   } else {
  //     prevTask = '';
  //   }

  //   this.updateServiceData()
  // }

  private updateServiceData() {
    this.ganttService.updateAllTaskInfo();
  }

  public createNotification = (type, title, message) => {
    this._notification.create(type, title, message);
  }

  // private checkPrevTask(prevArray, id, eq) {
  //   let allTasks = this.ganttService.allTasks;
  //   let length = allTasks.length
  //   for (let i = 0; i < prevArray.length; i++) {
  //     let int = prevArray[i];
  //     // 检查是否含有非法字符和非正整数字符
  //     let reg = /^\+?[1-9][0-9]*$/;
  //     if (isNaN(int) || !reg.test(int) || int > length) {
  //       this.elementRef.nativeElement.querySelector(`.task-list>.row:nth-child(${eq + 1})`).querySelector('.prevtask input').focus()
  //       this.createNotification('error', '请检查', '前置任务不存在')
  //       return false;
  //     }
  //     // 检查前置任务时间不能为空
  //     if (!allTasks[int - 1].startDate || !allTasks[int - 1].endDate) {
  //       this.elementRef.nativeElement.querySelector(`.task-list>.row:nth-child(${eq + 1})`).querySelector('.prevtask input').focus()
  //       this.createNotification('error', '请检查', '前置任务时间不能为空')
  //       return false;
  //     }

  //     // 检查是否前置任务是自己
  //     if (int == id) {
  //       this.elementRef.nativeElement.querySelector(`.task-list>.row:nth-child(${eq + 1})`).querySelector('.prevtask input').focus()
  //       this.createNotification('error', '请检查', '前置任务不能是自己')
  //       return false;
  //     }
  //     // 检查是否是循环
  //     // let check = this.searchLoop(this.ganttService.prevTaskIDInfo, int, id)
  //     // if (!check) {
  //     //   this.elementRef.nativeElement.querySelector(`.task-list>.row:nth-child(${eq + 1})`).querySelector('.prevtask input').focus()
  //     //   this.createNotification('error', '请检查', '已产生循环')
  //     //   return false;
  //     // }
  //   }

  //   return true
  // }

  // private searchLoop(prev, node, key) {
  //   var n = prev[node - 1]
  //   if (!n || n.length === 0) {
  //     return true;
  //   }
  //   else {
  //     if (n.indexOf(key) !== -1)
  //       return false;
  //     else {
  //       for (let i = 0; i < n.length; i++) {
  //         if (this.searchLoop(prev, n[i], key) === false)
  //           return false;
  //       }
  //       return true;
  //     }
  //   }
  // }

  private foldTaskLevel(task) {
    let index = task.id - 1;

    let allTasks = this.ganttService.allTasks;
    let children = allTasks[index].childTaskID;

    for (let i = 0; i < children.length; i++) {
      const child = children[i] - 1;
      allTasks[child].IsSelected = false;
    }

    allTasks[index].isFold = true;
    this.ganttService.updateAllTaskInfo();
  }

  private openTaskLevel(task) {
    let index = task.id - 1;
    this.ganttService.allTasks[index].isFold = false;
    this.ganttService.updateAllTaskInfo();
  }

  public getChildPadding(task) {
    let padding = (task.level) * 10;
    return padding;
  }

  // 全选
  public selectAllTask() {
    this.ganttService.IsAllSelected = this.isAllselected;
    this.ganttService.selectAllTask();
  }


  public clickTaskName(task) {
    this.ganttService.clickTaskName(task);
  }

  public clickCheckBox(task) {
    this.ganttService.clickCheckBox(task);
  }

  public showBinds(task) {
    console.log(task);
    this.modelService.currentTask = task;
    let bindings = task.bindings;
    let param = new Object();
    // if (bindings && bindings.length > 0) {
    //   this.ganttApi.renderFinishedMode(task.symbol);
    //   let data = this.ganttApi.getTaskPros(task.symbol);
      
    // } else {
    //   this.createNotification('error', '请检查', '请先绑定构件')
    // }
  }

  public submitFinishBinds() {
    this.ganttService.saveTasksHanle('save');
  }

  public getActualDate(date) {
    if (date) {
      return moment(date).format('YYYY-MM-DD');
    } else {
      return false;
    }
  }



}
